<template>
  <div class="add-clothes-container">
    <div class="page-header">
      <van-icon name="arrow-left" class="back-icon" @click="handleBack" />
      <span class="page-title">属性详情</span>
    </div>

    <div v-if="loading" class="loading-state">
      <van-loading type="spinner" />加载中...
    </div>

    <div v-else class="form-container">
      <!-- 备注信息 -->
      <div class="form-group">
        <div class="description" @click="showDescriptionPopup = true">
          {{ form.description || "添加备注" }}
        </div>
      </div>

      <!-- 季节选择 -->
      <div class="form-group season-group">
        <div>季节</div>
        <div class="season-options-row">
          <div
            v-for="season in seasons"
            :key="season"
            :class="[
              'season-option-btn',
              form.seasons.includes(season) ? 'selected' : '',
            ]"
            @click="toggleSeason(season)"
          >
            {{ season }}
          </div>
        </div>
      </div>

      <!-- 适合场景选择 -->
      <div class="form-group">
        <van-field
          input-align="right"
          is-link
          readonly
          label="适合场景"
          label-width="auto"
          @click="showOccasionPopup = true"
          style="padding: 0"
        >
          <template #button>
            <div
              v-if="form.occasions.length > 0"
              style="color: #c8c9cc; font-size: 14px"
            >
              {{ form.occasions.join(" ") }}
            </div>
            <div v-else style="color: #c8c9cc">请选择</div>
          </template>
        </van-field>
      </div>
    </div>

    <!-- 备注弹窗 -->
    <van-popup
      v-model:show="showDescriptionPopup"
      position="bottom"
      :round="true"
    >
      <div class="popup-header">
        <span>添加备注</span>
      </div>
      <div class="description-input">
        <van-field
          v-model="tempDescription"
          type="textarea"
          rows="4"
          placeholder="添加备注"
          style="
            background-color: #f5f5f5;
            border-radius: 10px;
            border: 1px solid #ccc;
          "
        />
      </div>
      <div class="picker-bottom">
        <div class="popup-actions">
          <div class="cancel-btn" @click="onDescriptionCancel">取消</div>
          <div class="confirm-btn" @click="onDescriptionConfirm">确认</div>
        </div>
      </div>
    </van-popup>

    <!-- 场合选择弹窗 -->
    <van-popup v-model:show="showOccasionPopup" position="bottom" :round="true">
      <div class="popup-header">
        <span>选择适合场景</span>
      </div>
      <div class="occasion-options-horizontal">
        <div
          v-for="occasion in allOccasions"
          :key="occasion.value"
          :class="[
            'occasion-option',
            tempOccasions.includes(occasion.value)
              ? 'occasion-option-selected'
              : '',
          ]"
          @click="toggleOccasion(occasion.value)"
        >
          <span
            class="occasion-checkbox"
            v-if="tempOccasions.includes(occasion.value)"
            >✓</span
          >
          <span>{{ occasion.text }}</span>
        </div>
      </div>
      <div class="picker-bottom">
        <div class="popup-actions">
          <div class="cancel-btn" @click="onOccasionCancel">取消</div>
          <div class="confirm-btn" @click="onOccasionConfirm">确认</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useOutfitStore } from "../store/outfit";
import { showToast } from "vant";

const router = useRouter();
const route = useRoute();
const outfitStore = useOutfitStore();
const outfitId = ref(route.params.id);
const loading = ref(false);

// 表单数据
const form = ref({
  description: "",
  seasons: [],
  occasions: [],
});

// 初始表单数据，用于比较是否有变更
const initialFormData = ref(null);

// 临时变量
const tempDescription = ref("");
const tempOccasions = ref([]);

// 季节选择
const seasons = ["春", "夏", "秋", "冬"];

// 场景选择选项
const allOccasions = [
  { text: "工作", value: "工作" },
  { text: "休闲", value: "休闲" },
  { text: "运动", value: "运动" },
  { text: "旅行", value: "旅行" },
  { text: "约会", value: "约会" },
  { text: "派对", value: "派对" },
];

// 弹窗状态
const showDescriptionPopup = ref(false);
const showOccasionPopup = ref(false);

// 切换季节选择
const toggleSeason = (season) => {
  if (form.value.seasons.includes(season)) {
    // 如果已选中，则取消选中
    form.value.seasons = form.value.seasons.filter((s) => s !== season);
  } else {
    // 如果未选中，则添加选中
    form.value.seasons.push(season);
  }
};

// 切换场合选择（在弹窗中）
const toggleOccasion = (occasion) => {
  if (tempOccasions.value.includes(occasion)) {
    // 如果已选中，则取消选中
    tempOccasions.value = tempOccasions.value.filter((o) => o !== occasion);
  } else {
    // 如果未选中，则添加选中
    tempOccasions.value.push(occasion);
  }
};

// 描述选择取消
const onDescriptionCancel = () => {
  tempDescription.value = "";
  showDescriptionPopup.value = false;
};

// 描述选择确认
const onDescriptionConfirm = () => {
  form.value.description = tempDescription.value;
  showDescriptionPopup.value = false;
};

// 场合选择取消
const onOccasionCancel = () => {
  tempOccasions.value = [...form.value.occasions];
  showOccasionPopup.value = false;
};

// 场合选择确认
const onOccasionConfirm = () => {
  form.value.occasions = [...tempOccasions.value];
  showOccasionPopup.value = false;
};

// 加载搭配数据
const loadOutfitData = async () => {
  loading.value = true;
  try {
    const outfit = await outfitStore.fetchOutfitDetail(outfitId.value);
    // 赋值到对应的字段
    form.value.description = outfit.description || "";
    form.value.seasons = outfit.seasons || [];
    form.value.occasions = outfit.occasions || [];

    // 保存初始数据的深拷贝，用于后续比较
    initialFormData.value = JSON.parse(JSON.stringify(form.value));

    // 初始化临时变量
    tempDescription.value = form.value.description;
    tempOccasions.value = [...form.value.occasions];
  } catch (error) {
    console.error("加载搭配数据失败:", error);
    showToast((error && error.message) || "加载搭配数据失败，请稍后重试");
    router.back();
  } finally {
    loading.value = false;
  }
};

// 比较表单数据是否发生变化
const isFormDataChanged = () => {
  if (!initialFormData.value) return false;

  // 深拷贝当前表单数据进行比较
  const currentFormCopy = JSON.parse(JSON.stringify(form.value));
  const initialFormCopy = JSON.parse(JSON.stringify(initialFormData.value));

  // 比较两个对象是否相等
  return JSON.stringify(currentFormCopy) !== JSON.stringify(initialFormCopy);
};

// 保存数据
const saveData = async () => {
  try {
    // 准备提交数据
    const submitData = {
      ...form.value,
    };

    // 调用更新搭配接口
    await outfitStore.updateOutfit(outfitId.value, submitData);

    // 更新初始数据，避免返回时再次提示保存
    initialFormData.value = JSON.parse(JSON.stringify(form.value));

    return true;
  } catch (error) {
    console.error("更新搭配失败:", error);
    showToast({
      message: "保存数据失败，请稍后重试",
      position: "bottom",
      duration: 2000,
    });
    return false;
  }
};

// 返回上一页
const handleBack = async () => {
  // 检查表单数据是否发生变化
  if (isFormDataChanged()) {
    const success = await saveData();
    if (!success) {
      return; // 如果保存失败，不返回上一页
    }
  }
  // 返回上一页
  router.back();
};

// 页面挂载时，加载数据
onMounted(() => {
  loadOutfitData();
});
</script>

<style scoped>
* {
  font-size: 16px;
}
.add-clothes-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.page-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background-color: #f8f8f8;
}

.back-icon {
  font-size: 20px;
  color: #000000;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #000000;
  margin: 0 auto;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #999;
}

.form-container {
  margin: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
}

.description {
  color: #c8c9cc;
  height: 2.8em; /* 固定为两行文字的高度 */
  line-height: 1.4em; /* 设置行高 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  display: -webkit-box; /* 设置为弹性盒 */
  -webkit-line-clamp: 2; /* 限制显示行数 */
  -webkit-box-orient: vertical; /* 设置垂直排列 */
  word-break: break-all; /* 允许在单词内换行 */
}

.description-input {
  padding: 15px;
  word-break: break-all;
}

/* 季节选择样式 */
.season-group {
  display: flex;
  text-align: center;
  justify-content: space-between;
}

.season-options-row {
  display: flex;
  gap: 10px;
}

.season-group div {
  text-align: center;
}

.season-option-btn {
  padding: 2px 14px;
  border-radius: 20px;
  border: 1.5px solid #c8c9cc;
  color: #c8c9cc;
  font-size: 14px;
  text-align: center;
  cursor: default;
  user-select: none;
  white-space: nowrap;
}

.season-option-btn.selected {
  background-color: #000000;
  color: #fff;
  border: 1.5px solid #000000;
}

/* 场景选择样式 */
.occasion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.selected-occasions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 4px 0;
  min-height: 32px;
}

.occasion-tag {
  background-color: #f0f0f0;
  color: #666;
  padding: 4px 12px;
  border-radius: 16px;
  margin-right: 8px;
  margin-bottom: 8px;
  font-size: 14px;
}

.placeholder-text {
  color: #999;
}

/* 场合选择弹窗样式 */
.occasion-options-horizontal {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 10px 20px;
}

.occasion-option {
  flex: 0 0 calc(33.333% - 8px);
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fff;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  white-space: nowrap;
  font-size: 14px;
  font-weight: 500;
  position: relative;
}

.occasion-checkbox {
  margin-right: 4px;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
}

/* .occasion-option:hover {
  border-color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.15);
} */

.occasion-option-selected {
  background-color: #6c63ff;
  /* border-color: #6c63ff; */
  color: #fff;
  /* box-shadow: 0 4px 12px rgba(64, 158, 255, 0.25); */
}

/* .occasion-option-selected:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
} */

/* 弹窗通用样式 */
.popup-header {
  text-align: center;
  margin: 20px;
}

.popup-header span {
  color: #000;
  font-size: 16px;
  font-weight: bold;
}

.picker-bottom {
  padding: 15px 0 35px 0;
  width: 60%;
  margin: 0 auto;
}

.popup-actions {
  background-color: #f0f0f0;
  border-radius: 8px;
  display: flex;
  justify-content: center;
}

.cancel-btn,
.confirm-btn {
  width: 50%;
  border-radius: 8px;
  transition: all 0.3s ease;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  color: #000000;
}

.confirm-btn {
  background-color: #000000;
  color: #f0f0f0;
}

.cancel-btn:hover,
.confirm-btn:hover {
  transition: background-color 0.3s;
}

/* 处理中提示 */
.processing-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
}

.processing-content {
  background-color: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.processing-content p {
  margin-top: 15px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-container {
    margin: 20px;
  }
}
</style>
